package com.zx.idc.backend.gui.api.ftp.sftp;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.zx.idc.backend.gui.api.ftp.FtpClientConfig;
import com.zx.idc.common.pool.ObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * ChannelSftp 工厂类
 *
 * @author rxliuli
 */
public class SftpSessionFactory implements ObjectFactory<Session> {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private FtpClientConfig ftpClientConfig;

    public SftpSessionFactory(FtpClientConfig ftpClientConfig) {
        this.ftpClientConfig = ftpClientConfig;
    }

    @Override
    public Session createNew() {
        final JSch jSch = new JSch();
        try {
            final Session session = jSch.getSession(ftpClientConfig.getUsername(), ftpClientConfig.getHost(), ftpClientConfig.getPort());
            session.setPassword(ftpClientConfig.getPassword());
            final Properties properties = new Properties();
            properties.put("StrictHostKeyChecking", ftpClientConfig.getStrictHostKeyChecking());
            session.setConfig(properties);
            session.connect();
            log.info("JSch open ftp session successful: {}", session);
            return session;
        } catch (JSchException e) {
            throw new RuntimeException(e);
        }
    }
}
